<template>
	<view> 
		 
		<view class="content">

			<view class="trade">
				<!-- 买入 -->
				<view class="trade-inner">
					<view class="tab">
						<view class="buy bg-green" :class="type == 2 ? 'normal' : ''" @click="onChangeType(1)">{{i18n.trade.buy}}</view>
						<view class="sell uni-bg-down " :class="type == 1 ? 'normal' : ''" @click="onChangeType(2)">{{i18n.trade.sale}}</view>
						<view class="parallelogram"></view>
					</view>
					<view v-show="type == 1">
						<!-- 价格 -->
						<view class="flex text-center margin-top margin-bottom-sm">
							<view class="flex-sub padding" @tap="downbuyprice"> - </view>
							<view class="flex-treble padding">
								<input type="number" v-model="buyfrom.price" placeholder="价格" />
							</view>
							<view class="flex-sub padding" @tap="upbuyprice"> + </view>
						</view>
						<!-- <view class="uni-h7 uni-text-gray">≈{{buycny}} CNY</view> -->
						<view class="uni-h7 uni-text-gray">≈{{buyusd}} USD</view>
						<!-- 数量 -->
						<view class="flex text-center margin-top-sm margin-bottom-sm">
							<view class="flex-sub padding" @tap="downbuynum"> - </view>
							<view class="flex-treble padding">
								<input type="number" v-model="buyfrom.num" placeholder="数量" />
							</view>
							<view class="flex-sub padding" @tap="upbuynum"> + </view>
						</view>
						<view class="uni-h7 uni-text-gray">{{i18n.trade.available}} {{buyuse}}{{buyname}}</view>

						<slider activeColor="#00B48E" value="0" min="0" max="100" show-value @changing="buycatcu" />
						<view class="uni-h5">{{buytrade}} {{buyname}}</view>
						<!-- <view class="uni-h5 cny text-gray">≈{{buytradecny}} CNY</view> -->
						<view class="uni-h5 cny text-gray">≈{{buytradeusd}} USD</view>
						<button class="btn bg-green" @tap="gobuy">{{i18n.trade.buy}}</button>
					</view>
					<!-- 卖出 -->
					<view v-show="type == 2">
						<!-- 价格 -->
						<view class="flex text-center margin-top margin-bottom-sm">
							<view class="flex-sub padding" @tap="downsaleprice"> - </view>
							<view class="flex-treble padding">
								<input type="number" v-model="salefrom.price" placeholder="价格" />
							</view>
							<view class="flex-sub padding" @tap="upsaleprice"> + </view>
						</view>
						<!-- <view class="uni-h7 uni-text-gray">≈{{salecny}} CNY</view> -->
						<view class="uni-h7 uni-text-gray">≈{{saleusd}} USD</view>
						<!-- 数量 -->
						<view class="flex text-center margin-top-sm margin-bottom-sm">
							<view class="flex-sub padding" @tap="downsalenum"> - </view>
							<view class="flex-treble padding">
								<input type="number" v-model="salefrom.num" placeholder="数量" />
							</view>
							<view class="flex-sub padding" @tap="upsalenum"> + </view>
						</view>
						<view class="uni-h7 uni-text-gray">{{i18n.trade.available}} {{saleuse}}{{salename}}</view>

						<slider activeColor="#d14b64" value="0" min="0" max="100" show-value @changing="salecatcu" />
						<view class="uni-h5">{{saletrade}} {{buyname}}</view>
						<!-- <view class="uni-h5 cny text-gray">≈{{saletradecny}} CNY</view> -->
						<view class="uni-h5 cny text-gray">≈{{saletradeusd}} USD</view>
						<button class="btn uni-bg-down" @tap="gosale">{{i18n.trade.sale}}</button>
					</view>
				</view>
			</view>
			<view class="position">
				<view class="pmain">
					<view class="item">
						<text class="price">{{i18n.trade.price}}</text>
						<text class="num">{{i18n.trade.number}}</text>
					</view>

					<view class="item uni-down" v-for="(item,index) in saleList">
						<text class="price" @tap="setprice(item.price)">{{item.price}}</text>
						<text class="num">{{item.num}}</text>
						<view class="bg buybg" :style="[{ width:item.num/buynummax*100+'%'}]"></view>
					</view>

					<view>
						<view class="row margin-right" @tap="setprice(now)">
							{{now}}
						</view>
						<!-- <view class="row text-gray text-xs">
							≈{{cnyprice}} CNY
						</view> -->
						<view class="row text-gray text-xs">
							≈{{usdprice}} USD
						</view>
					</view>

					<view class="item uni-up" v-for="(item,index) in buyList">
						<text class="price" @tap="setprice(item.price)">{{item.price}}</text>
						<text class="num">{{item.num}}</text>
						<view class="bg sellbg" :style="[{ width:item.num/salenummax*100+'%'}]"></view>
					</view>

					<!-- <view class="depth uni-thinner-border" @click="depthClick">
						<view class="uni-h6">深度{{depthValue}}</view>
						<view class="popover-wrap" v-show="popoverVisible">
							<view class="kailong"></view>
							<view class="popover uni-thinner-border">
								<view class="item uni-divider" @click="depthChange(1)">1</view>
								<view class="item uni-divider" @click="depthChange(2)">2</view>
								<view class="item uni-divider" @click="depthChange(3)">3</view>
								<view class="item uni-divider" @click="depthChange(4)">4</view>
							</view>
						</view>
					</view> -->
				</view>
			</view>
		</view>
		<!-- 委托 -->
		<entrustOrderList :ptype1="ptype1" :ptype2="ptype2" :salename="salename" :buyname="buyname" ref="child"></entrustOrderList>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	import {
		uniDrawer
	} from '@dcloudio/uni-ui'
	// import positionList from '@/components/positionList.vue'
	import entrustOrderList from '@/components/entrustOrderList.vue'
	
	// import tradePanel from '@/components/tradePanel.vue'
	import {
		feed
	} from '@/kline/datafeeds/datafees.js';
	import Event from '@/kline/datafeeds/event.js'
	export default {  
		destroyed() {
			// this.$refs.trade.onChangeType(1) 
			this.cleartimer();
			//缓存
			uni.setStorage({
				key: 'binfo',
				data: this.binfo,
			})
		},
		
		components: {
			uniDrawer,
			// positionList,
			entrustOrderList, 
			// tradePanel, 
		},
		data() {
			return {
				symbol: 'BTCUSDT',
				market: {},
				binfo: {},
				drawerVisible: false,
				popoverVisible: false,
				scrollLeft: 0,
				areaList: [],
				marketList: [],
				buyList: [],
				saleList: [],
				orderList: [],
				buynummax: 1,
				salenummax: 1,
				depthValue: 1,
				type: 1, 
				buyname: '--',
				salename: '--',
				high: 99,
				low: 99,
				close: 99,
				volume: 999,
				change: 0,
				datafeeds: new feed(),
				buyfrom: {
					price: 0,
					num: 0,
				},
				salefrom: {
					price: 0,
					num: 0,
				},
				rule: {
					name: "BTC_USDT",
					round: "4",
					fee_buy: "0.00",
					fee_sell: "0.00",
					buy_min: "0.0001",
					buy_max: "10000000",
					sell_min: "0.0001",
					sell_max: "10000000",
					trade_min: "0.0001",
					trade_max: "10000000",
					trade_buy_num_min: "0.0001",
					trade_buy_num_max: "10000000",
					trade_sell_num_min: "0.0001",
					trade_sell_num_max: "10000000"
				},
				modalName: null,
				radio: '',
				marketList: {},
				// buyuse: , //买入可用
				// saleuse: 100, //卖出可用 
			}
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
				myconfig: state => state.user.myconfig
			}),
			hasLogin() {
				return this.userinfo.id ? true : false
			},
			ptype1() {
				return this.myconfig.cointype2[this.salename];
			},
			ptype2() {
				return this.myconfig.cointype2[this.buyname];
			},
			buyuse() {
				return this.userinfo['wall1'] ? this.userinfo[this.myconfig.cointype2[this.buyname]] : 0;
			},
			saleuse() {
				return this.userinfo['wall1'] ? this.userinfo[this.myconfig.cointype2[this.salename]] : 0;
			},
			now() {
				return this.close ? this.close : '';
			},
			cnyprice() {
				return Math.round(this.close * this.myconfig.rate_cny2usdt * 100) / 100;
			}, 
			buycny() {
				return Math.round(this.buyfrom.price * this.myconfig.rate_cny2usdt * 100) / 100;
			},
			salecny() {
				return Math.round(this.salefrom.price * this.myconfig.rate_cny2usdt * 100) / 100;
			},
			buytradecny() {
				return Math.round(this.buytrade * this.myconfig.rate_cny2usdt * 100) / 100;
			},
			saletradecny() {
				return Math.round(this.saletrade * this.myconfig.rate_cny2usdt * 100) / 100;
			},
			usdprice() {
				return Math.round(this.close * this.myconfig.rate_usdt2usd * 100) / 100;
			},
		    buyusd() {
				return Math.round(this.buyfrom.price * this.myconfig.rate_usdt2usd * 100) / 100;
			},
			saleusd() {
				return Math.round(this.salefrom.price * this.myconfig.rate_usdt2usd * 100) / 100;
			},
			buytradeusd() {
				return Math.round(this.buytrade * this.myconfig.rate_usdt2usd * 100) / 100;
			},
			saletradeusd() {
				return Math.round(this.saletrade * this.myconfig.rate_usdt2usd * 100) / 100;
			},
			buytrade() {
				return (this.buyfrom.price * this.buyfrom.num).toFixed(4);
			},
			saletrade() {
				return (this.salefrom.price * this.salefrom.num).toFixed(4);
			},
			i18n() {
				return this.$t('message');
			},

		},
		mounted() {
			console.log('bb')
			this.cleartimer();
			this.init();
			this.areaList = [{
				id: 1,
				name: "USDT"
			}, {
				id: 2,
				name: "BTC"
			}, {
				id: 3,
				name: "ETH"
			}, {
				id: 4,
				name: "EOS"
			}];



			this.orderList = [];


		},
		methods: {
			...mapActions(['getUserinfo']),
			tradetimer(){},
			init() {
				clearInterval(this.tradetimer)
				let data = uni.getStorageSync('market');
				console.log(data)
				this.symbol = data.symbol ? data.symbol : 'tmusdt';
				this.salename = data.name ? data.name.toUpperCase() : this.myconfig.c_pname;
				this.buyname = data.priceUnit ? data.priceUnit : 'USDT';
				// this.symbol = 'tmusdt';
				// this.salename = this.myconfig.c_pname;
				// this.buyname = 'USDT';
				uni.setNavigationBarTitle({
					title: this.salename.toUpperCase() + '/' + this.buyname
				});
				this.binfo = uni.getStorageSync('binfo');
				// console.log(this.binfo)
				// console.log(this.binfo[this.salename].price)
				this.close = parseFloat(this.binfo[this.salename.toLowerCase()].price);
				this.setprice(this.close);
				this.marketList = uni.getStorageSync('marketList');
				this.getcoinlist();
				this.sim()
				this.tradetimer = setInterval((e) => {
					 this.sim() 


					this.getcoinlist() //价格
					// console.log('===')
				}, 1500);
				 

				//获取市场配置
				this.$http.post('market', {
					name: this.salename + '_' + this.buyname
				}).then(res => { 
					if (res.data !== null) {
						this.rule = res.data
					}

				})
				setTimeout(() => {
					this.$refs.child.loadTabbars();
					// this.$refs.child.loadNewsList('refresh'); //刷新委托列表
				}, 300)

			},
			sim(){
				if (this.ptype1 !== 'wall10') {
					//模拟行情 委托单
					let nowprice = this.close;
					let wei=this.binfo[this.salename.toLowerCase()].price_precision
					 
					let a = [];
					let b = [];
					let offset = nowprice * 0.3 * Math.random();
					let cc = this.unit == 2 ? 1 : this.rule.round;
					for (let i = 0; i < 8; i++) {
						a[i] = {
							'price':(nowprice - offset * i * 0.01).toFixed(wei),
							'num': Math.round(Math.random() * 10000 * cc)
						}
					}
					for (let k = 0; k < 8; k++) {
						b[k] = {
							'price': (nowprice + offset * k * 0.01).toFixed(wei),
							'num': Math.round(Math.random() * 10000 * cc)
						}
					}
					this.saleList = b.reverse();
					this.buyList = a;
					this.getmax(this.buyList, 'buy');
					this.getmax(this.saleList, 'sale');
				} else {
					//真实行情 委托单
					let send = {
						ptype1: this.ptype1,
						ptype2: this.ptype2,
					}
					this.$http.post('trade.buylist', send).then(res => {
						console.log(res)
						if (res.code == 1) {
							this.saleList = res.data.salelist;
							this.buyList = res.data.buylist;
							this.getmax(this.buyList, 'buy');
							this.getmax(this.saleList, 'sale');
						}
					})
				}
			},
			changemarket(index) {
				console.log(index)
				uni.setStorageSync('market', this.marketList[index]);
				this.hideModal();
				this.init();
			
			},
			cleartimer() { 
				clearInterval(this.tradetimer)
			},
			getcoinlist() {
				//行情列表
				this.$http.post('btc.binfo').then(res => {
					this.binfo = res.data;
					this.close = parseFloat(this.binfo[this.salename.toLowerCase()].price);
				})
			},
			closeDrawer() {
				this.drawerVisible = false;
			},
			onChangeType(e) {
				this.type = e;
			},
			depthClick(e) {
				this.popoverVisible = !this.popoverVisible;
			},
			depthChange(e) {
				this.depthValue = e;
				this.$emit('depthChange', e);
			},
			getmax(list, type) {
				var arr = [];
				for (var i = 1; i < list.length; i++) {
					arr.push(list[i]['num']);
				}
				if (type == 'buy') {
					this.buynummax = Math.max(...arr);
				} else {
					this.salenummax = Math.max(...arr);
				}
			},
			nowtime() {
				// Event.off('data'); 
				// Event.on('data', data => { 
				// 	let newdata = data[data.length - 1];
				// 	this.setprice(newdata.close)
				// 	this.high = newdata.high;
				// 	this.low = newdata.low;
				// 	this.close = newdata.close;
				// 	this.volume = Math.round(newdata.vol * 100) / 100;
				// 	this.change = Math.round((newdata.close - newdata.open) / newdata.open * 10000) / 100;
				// 	console.log('数据'+this.salename)
				// 	console.log(newdata)
				// })

				// // 拿到实时数据 在这里画
				Event.on('realTime', data => {

					this.high = data.high;
					this.low = data.low;
					this.close = data.close;
					this.volume = Math.round(data.vol * 100) / 100;
					this.change = Math.round((data.close - data.open) / data.open * 10000) / 100;
					console.log('realTime' + this.salename)
					console.log(this.close)
				})
			},
			realtime() {
				setTimeout(() => {
					this.nowtime();
				}, 1000)

			},
			setprice(price) {
				this.buyfrom.price = price;
				this.salefrom.price = price;
			},
			//加法
			accAdd(arg1, arg2) {
				var r1, r2, m, n;
				try {
					r1 = arg1.toString().split(".")[1].length
				} catch (e) {
					r1 = 0
				}
				try {
					r2 = arg2.toString().split(".")[1].length
				} catch (e) {
					r2 = 0
				}
				m = Math.pow(10, Math.max(r1, r2));
				//last modify by deeka
				//动态控制精度长度
				n = (r1 >= r2) ? r1 : r2;
				var ree = ((arg1 * m + arg2 * m) / m).toFixed(n);
				return ree > 0 ? ree : 0;
			},
			//减法
			accSub(arg1, arg2) {
				return this.accAdd(arg1, -arg2);
			},
			downbuyprice() {
				this.buyfrom.price = this.accSub(this.buyfrom.price, this.rule.buy_min);
			},
			upbuyprice() {
				this.buyfrom.price = this.accAdd(this.buyfrom.price, this.rule.buy_min);
			},
			downsaleprice() {
				this.salefrom.price = this.accSub(this.salefrom.price, this.rule.sell_min);
			},
			upsaleprice() {
				this.salefrom.price = this.accAdd(this.salefrom.price, this.rule.sell_min);
			},
			downbuynum() {
				this.buyfrom.num = this.accSub(this.buyfrom.num, this.rule.trade_buy_num_min);
			},
			upbuynum() {
				this.buyfrom.num = this.accAdd(this.buyfrom.num, this.rule.trade_buy_num_min);
			},
			downsalenum() {
				this.salefrom.num = this.accSub(this.salefrom.num, this.rule.trade_sell_num_min);
			},
			upsalenum() {
				this.salefrom.num = this.accAdd(this.salefrom.num, this.rule.trade_sell_num_min);
			},
			buycatcu(e) {

				// this.buytrade = (this.buyuse * e.detail.value / 100).toFixed(4);
				if (this.buyfrom.price > 0) {
					this.buyfrom.num = (this.buyuse * e.detail.value / 100 / this.buyfrom.price).toFixed(4);
				}
			},
			salecatcu(e) {

				// this.saletrade = (this.saleuse * e.detail.value * this.salefrom.price / 100).toFixed(4);
				this.salefrom.num = (this.saleuse * e.detail.value / 100).toFixed(4);
			},
			gobuy() {
				if (!this.hasLogin) {
					this.$api.msg(this.i18n.popup.loginfirst)
					return false;
				}
				if (this.buyfrom.num == 0) {
					this.$api.msg(this.i18n.popup.neednumber)
					return false;
				}
				if (this.buyfrom.num < this.rule.trade_buy_num_min) {
					this.$api.msg(this.i18n.trade.minnum + this.rule.trade_buy_num_min)
					return false;
				}
				if (this.buyfrom.price == 0) {
					this.$api.msg(this.i18n.popup.needprice)
					return false;
				}
				if (this.buyfrom.num * this.buyfrom.price < this.rule.trade_min) {
					this.$api.msg(this.i18n.trade.mixtrade  + this.rule.trade_min)
					return false;
				}

				this.buyfrom.ptype1 = this.ptype1;
				this.buyfrom.ptype2 = this.ptype2;
				this.$http.post('trade.buy', this.buyfrom).then(res => {
					console.log(res)
					if(res.code==1){
						this.$api.msg(this.i18n.popup.success); 
						this.getUserinfo();
						this.$refs.child.loadNewsList('refresh'); //刷新委托列表
					}else{
						this.$api.msg(res.msg)
					}
				})
			},
			gosale() {
				if (!this.hasLogin) {
					this.$api.msg(this.i18n.popup.loginfirst)
					return false;
				}
				if (this.salefrom.num == 0) {
					this.$api.msg(this.i18n.popup.neednumber)
					return false;
				}
				if (this.salefrom.num < this.rule.trade_sell_num_min) {
					this.$api.msg(this.i18n.trade.minnum  + this.rule.trade_sell_num_min)
					return false;
				}
				if (this.salefrom.price == 0) {
					this.$api.msg(this.i18n.popup.needprice)
					return false;
				}
				if (this.salefrom.num * this.salefrom.price < this.rule.trade_min) {
					this.$api.msg(this.i18n.trade.mixtrade + this.rule.trade_min)
					return false;
				}

				this.salefrom.ptype1 = this.ptype1;
				this.salefrom.ptype2 = this.ptype2;
				this.$http.post('trade.sale', this.salefrom).then(res => {
					console.log(res)
					if(res.code==1){
						this.$api.msg(this.i18n.popup.success); 
						this.getUserinfo();
						this.$refs.child.loadNewsList('refresh'); //刷新委托列表
					}else{
						this.$api.msg(res.msg)
					}
					 
				})
			},
			gocny() {
				uni.navigateTo({
					url: `/pages/trade2/main`
				})
			},
			showModal(name) {
				console.log(name)
				this.modalName = name
			},
			hideModal(e) {
				this.modalName = null
			},
			RadioChange(e) {
				uni.setStorageSync('market', this.marketList[e.detail.value]);
				this.init();
				this.radio = e.detail.value;
				this.hideModal();
			},
		}
	}
</script>

<style lang='scss'>
	.content {
		padding: 14px 0px;
		display: flex;
		background: $page-color-light;
		/* min-height: 570px; */
	}

	.content .trade {
		width: 60%;
		padding-left: 20upx;
		padding-right: 20upx;
	}

	.content .position {
		width: 40%;
	}

	.trade-inner {
		position: relative;
		height: 410px;
	}

	.trade-inner .tab {
		position: relative;
		display: flex;
		text-align: center;
	}

	.trade-inner .tab .buy {
		color: #ffffff;
		font-weight: bold;
		width: 50%;
		height: 70upx;
		line-height: 70upx;
	}

	.trade-inner .tab .sell {
		color: #ffffff;
		font-weight: bold;
		width: 50%;
		height: 70upx;
		line-height: 70upx;
	}

	.trade-inner .tab .normal {
		background: #ECECF6;
		color: #555555;
		font-weight: bold;
	}

	.trade-inner .tab .parallelogram {
		position: absolute;
		left: calc(50% - 21upx);
		top: 0;
		transform: translate(-50%, -50%);
		width: 40upx;
		height: 74upx;
		background: $page-color-light;
		;
		-webkit-transform: skew(-30deg);
		-moz-transform: skew(-30deg);
		-o-transform: skew(-30deg);
		transform: skew(-30deg);
	}

	.trade-inner .price-input {
		position: relative;
		margin-top: 30upx;
	}

	.trade-inner .price-input input {
		position: relative;
		padding-right: 180upx;
	}

	.trade-inner .price-input .opt {
		display: flex;
		position: absolute;
		top: 2upx;
		right: 0;
		width: 180upx;
		height: 78upx;
		line-height: 78upx;
	}

	.trade-inner .num-input {
		position: relative;
		margin-top: 30upx;
	}

	.trade-inner .price-input .opt .button {
		border: 0;
		background: #fff;
		width: 80upx;
		height: 78upx;
		line-height: 78upx;
		text-align: center;
		font-size: 48upx;
		font-weight: 400;
	}

	.trade-inner .btn {
		height: 74upx;
		line-height: 74upx;
		color: #fff;
		font-size: 28upx;
		font-weight: bold;
		bottom: 0px;
		position: absolute;
		width: 100%;
	}

	.flex-sub {
		border: solid 1px rgba(128, 128, 128, 0.16);
	}

	.flex-treble {
		border-top: solid 1px rgba(128, 128, 128, 0.16);
		border-bottom: solid 1px rgba(128, 128, 128, 0.16);
	}

	.padding {
		padding: 9px;
	}

	.pmain {
		width: 100%;
		height: 600upx;
		position: relative;
		justify-content: space-between;
		text-align: left;
	}

	.pmain .item {
		position: relative;
		width: 100%;
		display: flex;
		font-size: 24upx;
	}

	.pmain .item .bg {
		height: 100%;
		position: absolute;
		top: 0;
		right: 0;
		/* z-index: -9999; */
	}

	.buybg {
		background: rgba(222, 2, 3, 0.1);
		max-width: 100%;
	}

	.sellbg {
		background: rgba(44, 197, 153, 0.1);
		max-width: 100%;
	}

	.pmain .item .price {
		display: block;
		width: 40%;
		text-align: left;
	}

	.position .item .num {
		display: block;
		width: 60%;
		text-align: right;
		padding-right: 10upx;
	}

	.pmain .current-price {
		margin: 10upx 0;
	}

	.pmain .current-price .usdt {}

	.pmain .depth {
		position: relative;
		margin-top: 10upx;
		margin-right: 10upx;
	}

	.pmain .depth .uni-h6 {
		text-align: center;
		height: 60upx;
		line-height: 60upx;
	}

	.pmain .depth .popover {
		position: absolute;
		top: 80upx;
		width: 100%;
		z-index: 9999999999;
		background: #ffffff;
		display: inline-block;
		border-radius: 20px;
	}

	.pmain .depth .popover .item {
		width: 100%;
		height: 60upx;
		line-height: 60upx;
		display: block;
		text-align: center;
	}

	.pmain .depth .kailong {
		position: absolute;
		left: 50%;
		top: 74upx;
		transform: translate(-50%, -50%);
		max-width: 50%;
		width: 0;
		height: 0;
		border-right: 20px solid transparent;
		border-left: 20px solid transparent;
		border-bottom: 20px solid #E0E0E0;
	}

	.popover-wrap .uni-thinner-border:before {
		border-radius: 15px !important;
	}

	.row {
		display: inline;
		white-space: nowrap;
	}

	.uni-h5 {
		bottom: 95px;
		/* position: absolute; */
	}

	.uni-h5.cny {
		bottom: 62px;
	}

	.nav .cu-item.cur {
		border-bottom: 0px;
	}

	.cu-list.menu-avatar>.cu-item:after,
	.cu-list.menu>.cu-item:after {
		border-bottom: 0px;
	}
</style>
